<script>
export default {
  data() {
    return {
      rootValue: 'root',
      valueKey: 'code',
      parentValueKey: 'parent_code',
      list: [],
      selected: {}
    }
  },
  computed: {
    treeData() {
      return this.listToTree(this.list)
    }
  },
  methods: {
    isParent(parent, row) {
      return parent[this.parentValueKey] === row[this.valueKey]
    },
    indexOf(row) {
      const key = this.valueKey
      for (var i = 0; i < this.list.length; i++) {
        if (this.list[i][key] === row[key]) {
          return i
        }
      }
      return -1
    },
    listToTree(list) {
      const root = []
      const { valueKey, parentValueKey, rootValue } = this
      for (var i = 0; i < list.length; i++) {
        const parent = list[i]
        const children = list.filter((item) => {
          return parent[valueKey] === item[parentValueKey]
        })
        if (children.length !== 0) {
          parent.children = children
        }
        if (rootValue === parent[parentValueKey]) {
          root.push(parent)
        }
      }
      return root
    },
    selectable(row) {
      return row && row[this.valueKey]
    },
    isSelected(row) {
      const key = this.valueKey
      return row && this.selected[key] && row[key] === this.selected[key]
    },
    rowClass(row) {
      return {
        'selectable-node': this.selectable(row),
        'selected-node': this.isSelected(row)
      }
    },
    rowClick(row) {
      if (this.isSelected(row)) {
        return
      }
      this.selected = Object.assign({}, row)
      this.$emit('select', row)
    },
    clearSelected() {
      this.selected = {}
    }
  }
}
</script>
<style >
.tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.selected-node,
.selectable-node:hover {
  background-color: #409eff;
  border-radius: 4px;
  padding: 3px;
}
.selected-node:hover {
  opacity: 0.9;
}
.selectable-node:hover {
  opacity: 0.8;
}
</style>
